﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;

namespace FastNET.CleanAct.Client.Win32.Unmanaged
{
    internal class RegistryManipulation
    {
        #region Process Access Elevation

        [StructLayout(LayoutKind.Sequential)]
        public struct LUID
        {
            public int LowPart;
            public int HighPart;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct TOKEN_PRIVILEGES
        {
            internal int PrivilegeCount;
            //LUID_AND_ATRIBUTES
            [MarshalAs(UnmanagedType.ByValArray)]
            internal LUID_AND_ATRIBUTES[] Privileges;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct LUID_AND_ATRIBUTES
        {
            public LUID Luid;
            public int Attributes;
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern bool OpenProcessToken([In] IntPtr processToken, [In] TokenAccessLevels desiredAccess, [In, Out] ref IntPtr tokenHandle);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool LookupPrivilegeValue([In, MarshalAs(UnmanagedType.LPTStr)] string lpSystemName, [In, MarshalAs(UnmanagedType.LPTStr)] string lpName, [Out, MarshalAs(UnmanagedType.Struct)] out LUID lpLuid);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool AdjustTokenPrivileges([In] IntPtr tokenHandle, [In] bool disableAllPrivileges, [In] TOKEN_PRIVILEGES newState, [In] int bufferLength, [Out] out TOKEN_PRIVILEGES previousState, [Out] out int returnLength);

        #endregion


        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int RegLoadKey([In] uint hKey, [In, MarshalAs(UnmanagedType.LPTStr)] string lpSubKey, [In, MarshalAs(UnmanagedType.LPTStr)] string lpFile);
        
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int RegUnLoadKey([In] uint hKey, [In, MarshalAs(UnmanagedType.LPTStr)] string lpSubKey);


        public const int SE_PRIVILEGE_ENABLED = 0x00000002;
        public const string SE_RESTORE_NAME = "SeRestorePrivilege";
        public const string SE_BACKUP_NAME = "SeBackupPrivilege";


        public const uint HKEY_USERS = 0x80000003;

    }
}
